package com.itcast.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.itcast.tanhua.dubbo.server.domain.Visitors;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @PachageName: com.itcast.tanhua.dubbo.server.api
 * @ClassName:
 * @Description: TODO
 * @Author: Hushi
 * @DateTime: 2021/2/2619:47
 * @Version 1.0
 */
@Service(version = "1.0.0")
@Component
public class VisitorsApiImpl implements VisitorsApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveVisitor(Visitors visitors) {
        visitors.setId(ObjectId.get());
        visitors.setDate(System.currentTimeMillis());

        this.mongoTemplate.save(visitors);
        return visitors.getId().toHexString();
    }

    @Override
    public List<Visitors> topVisitor(Long userId, Integer num) {

        Pageable pageRequest = PageRequest.of(0,num, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        return this.queryVisitorList(query);
    }

    @Override
    public List<Visitors> topVisitor(Long userId, Long date) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("date").gte(date));
        return this.queryVisitorList(query);
    }

    private List<Visitors> queryVisitorList(Query query){
        List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class);
        if (!CollectionUtils.isEmpty(visitorsList)){
            for (Visitors visitors : visitorsList){
                Query queryVisitors = Query.query(Criteria.where("userId").is(visitors.getVisitorUserId()).and("toUserId").is(visitors.getUserId()));
                Visitors visitor = this.mongoTemplate.findOne(queryVisitors, Visitors.class);
                if (null != visitor){
                    visitors.setScore(visitor.getScore());
                }
                else{
                    visitors.setScore(30d);
                }
            }
        }
        return visitorsList;
    }

    @Override
    public List<Visitors> topVisitor(Long userId, Integer page, Integer pageSize) {
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageable);
        return this.queryVisitorList(query);
    }
}
